package org.lzy.shop.activity

import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout.OnRefreshListener
import org.lzy.shop.R
import org.lzy.shop.adapter.CustomMsgAdapter
import org.lzy.shop.base.BaseMvvmActivity
import org.lzy.shop.databinding.ActivityCustomMsgListBinding
import org.lzy.shop.response.Contents
import org.lzy.shop.response.ItemMsg
import org.lzy.shop.util.DataStoreUtils
import org.lzy.shop.viewmodel.MineModel
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 在线客服
 */
class CustomMsgListActivity : BaseMvvmActivity<ActivityCustomMsgListBinding, MineModel>({ ActivityCustomMsgListBinding.inflate(it) }),
    OnRefreshListener {

    var mPageIndex = 1
    private val customAdapter: CustomMsgAdapter by lazy { CustomMsgAdapter() }
    var sessionId: Int? = null
    // 添加一个列表来维护消息数据
    private val messageList = mutableListOf<ItemMsg>()
    // 定义本地存储的键名
    private val MSG_LIST_KEY = "customer_service_messages"
    private val SESSION_ID_KEY = "customer_service_session_id"

    private var lastRefreshTime: Long = 0

    private val REFRESH_INTERVAL = 5 * 60 * 1000L // 5分钟（单位：毫秒）


    override fun initView() {
        setTitleText(getResString(R.string.customer_service))
        binding.recyclerview.apply {
            layoutManager = LinearLayoutManager(this@CustomMsgListActivity)
            adapter = customAdapter
            setItemViewCacheSize(10)  // 减少缓存大小，根据实际情况调整
            setHasFixedSize(true)
        }
        binding.refreshLayout.apply {
            setOnRefreshListener(this@CustomMsgListActivity)
        }

        // 设置输入框监听
        binding.etMessage.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                // 根据输入框内容是否为空来控制发送按钮的显示和隐藏
                binding.btnSend.visibility = if (TextUtils.isEmpty(s)) {
                    android.view.View.GONE
                } else {
                    android.view.View.VISIBLE
                }
            }

            override fun afterTextChanged(s: Editable?) {}
        })

    }



    override fun initData() {
        mViewModel.createMsgData.observeWithLifecycle(this){createMsgResponse ->
            createMsgResponse?.let {
                val id = createMsgResponse.id
                mViewModel.getMsgList(id,mPageIndex.toString())

            }
        }
        mViewModel.msgListData.observeWithLifecycle(this){msgResponse ->
            finishRefresh()
            msgResponse?.let {
                if (msgResponse.isNotEmpty()) {
                    customAdapter.submitList(msgResponse)
                    msgResponse.reverse()
                }else{
                    showListEmpty()
                }
            }
        }
    }

    override fun requestData() {
        mViewModel.createMsg()

    }


    override fun onRefresh() {
        mPageIndex = 1
        mViewModel.createMsg()
    }

    override fun allClick() {
        // 发送按钮点击事件
        binding.btnSend.setOnClickListener { sendMessageClick() }
    }

    // 发送消息点击处理
    private fun sendMessageClick() {
        val message = binding.etMessage.text.toString()
        if (!TextUtils.isEmpty(message) && sessionId != null) {
            // 发送消息，此发送功能有点问题，正常逻辑来讲是走接口的
            sendMessage(message)
            // 清空输入框
            binding.etMessage.setText("")
        }
    }

    private fun finishRefresh() {
        binding.refreshLayout.isRefreshing = false
    }

    private fun showListEmpty() {
        customAdapter.submitList(null)
        customAdapter.isStateViewEnable = true
        customAdapter.stateView = showEmptyView()
    }

    // 模拟发送消息的方法
    private fun sendMessage(content: String) {
        // 创建一个新的消息对象
        val currentTime = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault()).format(Date())

        // 这里需要根据实际的ItemMsg结构来创建对象
        val newMessage = ItemMsg(
            adminUserHeadImg = "", // 客服头像
            adminUserName = "", // 客服名称
            avatarUrl = DataStoreUtils.getString("avatarUrl", ""), // 用户头像
            content = Contents(data = content, type = "text"), // 消息内容
            createTime = currentTime, // 创建时间
            id = "", // 消息ID
            nickName = DataStoreUtils.getString("nickName", "用户"), // 用户昵称
            sessionId = sessionId.toString(), // 会话ID
            status = 1, // 状态
            type = 0, // 0-用户发送，1-客服回复
            updateTime = currentTime, // 更新时间
            userId = DataStoreUtils.getString("userId", "") // 用户ID
        )

        // 将新消息添加到我们维护的列表中
        messageList.add(newMessage)
        // 更新适配器
        customAdapter.submitList(messageList.toList())

        // 滚动到底部
        binding.recyclerview.scrollToPosition(messageList.size - 1)

        // 注意：这里只是模拟，发送消息没有写
        if (sessionId != null) {
            mViewModel.sendMessage(sessionId, content)
        }
    }



}